
import pymysql
import xlwt

# 导出表中的数据，到Excel中去

def export():
    workbook = xlwt.Workbook()
    worksheet = workbook.add_sheet("sheet1")

    connect = pymysql.Connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='123456',
        db='bd36_user'
    )
    cursor = connect.cursor()
    export_to_excel(worksheet, cursor, 'douyin')
    cursor.close()
    connect.close()
    workbook.save("douyin表的数据.xlsx")


def export_to_excel(worksheet, cursor, table):

    """
    将MySQL一个数据表导出到excel文件的一个表的函数
    :param    worksheet:  准备写入的excel表
    :param    cursor:     源数据的数据库游标
    :param    table       源数据的数据表
    :return:  Nove.
    """
    # 首先向excel表中写入数据表的字段
    column_count = cursor.execute("desc %s"%table)
    for i in range(column_count):
       temptuple = cursor.fetchone()
       columnName = "车辆Vin码" if temptuple[0]=='vin' else  temptuple[0]
       worksheet.write(0, i, columnName)

    # 向构建好字段的excel表写入所有的数据记录
    row_count = cursor.execute("select * from %s"%table)
    for i in range(row_count):
        temptuple = cursor.fetchone()
        for j in range(column_count):
            worksheet.write(i + 1, j, temptuple[j])

if __name__ == '__main__':
    export()